<style lang="less">
@import "../../styles/common.less";
.blue-tag{
    margin:2px 4px;
    display: inline-block;
    padding:2px 6px;
    color:#fff;
    background:#2d8cf0;
}
</style>

<template>
  <div class="margin-top-10">
    <Row type="flex" justify="space-between">
      <Row>
        <Button type="primary" @click="handleAddClasscampus" style="margin-right: 3px">添加校区</Button>
      </Row>
      <Row>
        <Input
          v-model.trim="queryForm.group_name"
          @on-enter="searchCampus"
          placeholder="请输入集团名称"
          style="width: 150px;margin-right:3px"
        ></Input>
        <Input
          v-model.trim="queryForm.campus_name"
          @on-enter="searchCampus"
          placeholder="请输入校区名称"
          style="width: 150px;margin-right:3px"
        ></Input>
        <Button @click="searchCampus" type="primary">查询</Button>
      </Row>
    </Row>
    <div class="margin-top-10">
      <Table :columns="classcampusColumn" :data="classcampusData" :loading="tableLoading"></Table>
    </div>
    <Row type="flex" justify="end" class="margin-top-10">
      <Page
        :total="totalClasscampus"
        :current="currentPage"
        :page-size="pageSize"
        @on-change="getClasscampus"
        show-total
      >显示第{{currentIndex + 1}}-{{currentIndex + pageSize}}条，总数为{{totalClasscampus}}条</Page>
    </Row>

    <Modal
      v-model="addClasscampusModal"
      v-bind:title="modalTitle"
      :scrollable="true"
      class-name="vertical-center-modal"
      :mask-closable="false"
      @on-cancel="resetForm('classcampusInfoForm')"
      >
      <Form
        ref="classcampusInfoForm"
        :label-width="120"
        :model="classcampusInfo"
        :rules="classcampusInfoRules"
      >
        <FormItem label="集团名称" prop="group_id">
          <Select v-model="classcampusInfo.group_id" style="width:200px">
              <Option v-for="item in allGroupData" :value="item._id" :key="item._id">{{ item.group_name }}</Option>
          </Select>
        </FormItem>
        <FormItem label="校区名称" prop="campus_name">
            <Input v-model.trim="classcampusInfo.campus_name" :maxlength="30"  placeholder="请填写校区名称" />
        </FormItem>
        <FormItem label="校区ID（client）" prop="campus_id">
            <Input :disabled="!!classcampusInfo._id" v-model.trim="classcampusInfo.campus_id" :maxlength="30" placeholder="请填写校区ID" />
        </FormItem>
        <FormItem label="密匙（secret）" prop="secret">
            <Input v-model.trim="classcampusInfo.secret" :maxlength="30" placeholder="请填写secret" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary" @click="handleSubmitClasscampus('classcampusInfoForm')">提交</Button>
        <Button @click="addClasscampusModal=false">取消</Button>
      </div>
    </Modal>

  </div>
</template>

<script>
import {
  getClassgroup,
} from "../../controllers/classgroup";

import {
  getClasscampus,
  addClasscampus,
  updateClasscampus,
  deleteClasscampus,
} from "../../controllers/classcampus";

import Tooltip from "../../../node_modules/iview/src/components/tooltip/tooltip";
import Btn from "../../../node_modules/iview/src/components/button/button";
import Constant from "../../libs/constants";
import _ from "lodash";
import iconDelete from "../../images/delete.png";
import iconEdit from "../../images/edit.png";

import excelFile from "../../assets/staffExcel.xlsx";

export default {
  name:'classcampus',
  components: {
    Tooltip,
    Btn
  },
  data() {
    return {
      addClasscampusModal: false,
      tableLoading: true,
      queryForm:{
          group_name:'',
          campus_name:'',
      },
      allGroupData:[],//所有集团
      pageSize: Constant.PAGE_SIZE,
      currentPage: 1,
      totalClasscampus: 0,
      classcampusColumn: [
        {
          title: "集团名称",
          align: "center",
          key: "group_name",
          width: 200
        },
        {
          title: "校区名称",
          align: "center",
          key: "campus_name",
          width: 200
        },
        {
          title: "校区ID（client）",
          align: "center",
          key: "campus_id",
          minWidth: 200
        },
        {
          title: "密匙（secret）",
          key: "secret",
          align: "center",
          minWidth: 200,
        },
        {
          title: "操作",
          align: "center",
          width: 240,
          render: (h, { row, column, index }) => {
            const _id = row._id;
            return (
              <div class="operation">
                <Tooltip content="编辑" placement="bottom">
                  <Btn
                    style={{ background: `url( ${iconEdit})` }}
                    onClick={() => this.handleEditClasscampus(row)}
                  />
                </Tooltip>
                <Tooltip content="删除" placement="bottom">
                  <Btn
                    style={{ background: `url( ${iconDelete})` }}
                    onClick={() => this.handleDelClasscampus(row)}
                  />
                </Tooltip>
              </div>
            );
          }
        }
      ],
      classcampusData: [],
      ipcList:[],
      classcampusInfo: {
        _id:'',
        group_id:'',
        campus_id:'',
        campus_name:'',
        secret:''
      },
      modalTitle: "添加",
      classcampusInfoRules: {
          group_id: [
            { required: true, message: "请选择集团", trigger: "blur" }
          ],
          campus_id: [
            { required: true, message: "请输入校区ID", trigger: "blur" }
          ],
          campus_name: [
            { required: true, message: "请输入校区名称", trigger: "blur" }
          ],
          secret: [
            { required: true, message: "请输入secret", trigger: "blur" }
          ]
      },
    };
  },
  computed: {
    currentIndex: function() {
      return (this.currentPage - 1) * this.pageSize;
    },
  },
  //待考虑：初次加载表格的时机
  created() {
    this.getClassgroup()
    this.loadClasscampusData();
  },
  methods: {
    getClasscampus(page) {
      this.currentPage = page;
      this.tableLoading = true;
      this.loadClasscampusData();
    },
    getClassgroup(){
      getClassgroup({
        page_num:1, 
        page_size:1000, 
      }).then(res=>{
        if(res.code===0){
          this.allGroupData = res.data.result||[]
        }
      })
    },
    searchCampus() {
      //to-do:检验关键词
      this.currentPage = 1;
      this.tableLoading = true;
      this.loadClasscampusData();
    },
    loadClasscampusData() {
      getClasscampus({
          page_num:this.currentPage, 
          page_size:this.pageSize, 
          ...this.queryForm
        })
        .then(json => {
          let { total, data } = transclasscampusData(json);
          this.totalClasscampus = total;
          this.classcampusData = data;
          this.tableLoading = false;
          let tmp = _.map(data, item => item.uid);
          return tmp;
        })
        // .then(uids => this.asyncAvatar(uids));
    },
    resetForm(form) {
      //解决对话框消失的时候字体变化问题
      setTimeout(() => {
        this.$refs[form].resetFields();
        this.classcampusInfo._id = null;
      }, 500);
    },
    handleAddClasscampus(){
      this.modalTitle =  "添加校区"
      this.addClasscampusModal = true
      this.classcampusInfo._id = ''
      this.classcampusInfo.group_id = this.allGroupData.length?this.allGroupData[0]._id:''
      this.classcampusInfo.campus_name = ''
      this.classcampusInfo.campus_id = ''
      this.classcampusInfo.secret = ''
    },
    handleEditClasscampus(row){
      this.modalTitle =  "编辑校区"
      this.addClasscampusModal = true
      this.classcampusInfo._id = row._id
      this.classcampusInfo.group_id = row.group_id
      this.classcampusInfo.campus_name = row.campus_name
      this.classcampusInfo.campus_id = row.campus_id
      this.classcampusInfo.secret = row.secret
    },
    handleDelClasscampus(row){
      this.$Modal.confirm({
        title: "确认",
        content: "删除校区【" + row.campus_name + "】？",
        onOk: () => {
          deleteClasscampus({ campus_id: row.campus_id }).then(res => {
            if (res.code === 0) {
              this.$Message.success("删除成功!");
              this.loadClasscampusData();
            }
          });
        }
      });
    },
    handleSubmitClasscampus(){
      const submitInfo = Object.assign({},this.classcampusInfo)
      this.$refs['classcampusInfoForm'].validate(valid => {
        if (valid) {
          if(submitInfo._id){
            updateClasscampus(
                submitInfo
            ).then(res => {
                if (res.code == 0) {
                this.$Message.success("提交成功!");
                this.addClasscampusModal = false;
                this.resetForm('classcampusInfoForm');
                this.loadClasscampusData(this.current_group_id);
                }
            });
          }else{
            addClasscampus(
              submitInfo
            ).then(res => {
              if (res.code == 0) {
                this.$Message.success("提交成功!");
                this.addClasscampusModal = false;
                this.resetForm('classcampusInfoForm');
                this.loadClasscampusData(this.current_group_id);
              }
            });
          }
        } else {
          this.$Message.error("填写项目验证失败!");
        }
      });
    }
  }
};

function transclasscampusData(json) {
  //检测状态码
  if (json.code !== 0) {
    //非正常就返回空表
    return { total: 0, result: {} };
  }
  let data = json.data;
  //检测数据块存在及长度
  if (data === undefined) {
    return { total: 0, result: {} };
  }

  let { total, result } = data;

  return {
    total,
    data: result
  };
}

</script>